package com.tt.mymu.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tt.mymu.entity.User;
import com.tt.mymu.entity.UserView;
import com.tt.mymu.entity.po.UserPO;
import com.tt.mymu.entity.vo.UserVOEndTime;
import com.tt.mymu.mapper.UserMapper;
import com.tt.mymu.service.UserService;
import com.tt.mymu.service.UserViewService;
import com.tt.mymu.utils.AESEncrypter;
import com.tt.mymu.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Service
public class UserServiceImpl implements UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserViewService userViewService;

    @Override
    public Result loginUser(String userName, String password, HttpServletRequest request, HttpServletResponse response) {
        logger.info("登陆用户信息 {userName}");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        String token = null;
        try {

            queryWrapper.eq("user_name", userName);
            queryWrapper.eq("password", AESEncrypter.encrypt(password));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        User userLogin = userMapper.selectOne(queryWrapper);

        if (userLogin == null || userLogin.equals("")) {
            return Result.build(1, "登陆失败");
        }
        //request.getSession().setAttribute("user", userLogin);
        token = UUID.randomUUID().toString().replace("-", "");
        userLogin.setToken(token);
        userMapper.updateById(userLogin);
        //setCookie(token, request, response);
        userLogin.setPassword("***");
        return Result.success(userLogin);
    }

    @Override
    public Result registUser(User use, HttpServletRequest request, HttpServletResponse response) {
        User userRegist = new User();
        String token = null;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", use.getUserName());
        User userLogin = userMapper.selectOne(queryWrapper);
        if (userLogin == null || userLogin.equals("")) {
            try {
                userRegist.setUserName(use.getUserName());
                userRegist.setPassword(AESEncrypter.encrypt(use.getPassword()));
                userRegist.setAge(use.getAge());
                userRegist.setStatus(0);
                userRegist.setCreateTime(new Date());
                token = UUID.randomUUID().toString().replace("-", "");
                userRegist.setToken(token);
                userRegist.setRealName(use.getRealName());
                userRegist.setAddress(use.getAddress());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            int insert = userMapper.insert(userRegist);
            if (insert > 0) {
                UserView userView = new UserView();
                userView.setUserId(userRegist.getId());
                userView.setUserName(userRegist.getUserName());
                userView.setCreateTime(new Date());
                userViewService.insertUserViewByUser(userView);
                //request.getSession().setAttribute("user", userLogin);
                //setCookie(token, request, response);
                return Result.success(userRegist);
            }
            return Result.build(1, "登陆失败");
        }
        return Result.build(1, "用户已存在");
    }

    /*private void setCookie(String token, HttpServletRequest request, HttpServletResponse response) {
        // 创建一个cookie
        Cookie myCookie = new Cookie("expire", token);
        // 设置cookie的有效期，例如一个小时(3600秒)
        myCookie.setMaxAge(3600);
        myCookie.setPath("/");
        //myCookie.setPath(request.getContextPath());
        response.addCookie(myCookie);

    }*/

    @Override
    public Result deleteUser(int id) {
        int i = userMapper.deleteById(id);
        return Result.success(i);
    }

    @Override
    public Result updateUser(User user) {
        int i = userMapper.updateById(user);
        if (i > 0) {
            return Result.success(i);
        }
        return Result.build(1, "更新失败");
    }

    /**
     * 管理员登陆
     *
     * @param userPO
     * @param page
     * @param size
     * @return
     */
    @Override
    public Result getUserList(UserPO userPO, int page, int size) {
        PageHelper.startPage(page, size);

        if (null != userPO) {

            List<UserVOEndTime> users = userMapper.selectUserListOrEndTime(userPO);
            PageInfo<UserVOEndTime> pageInfo = new PageInfo(users);
            return Result.success(pageInfo);
        }
        return Result.build(1, "获取用户信息失败");
    }

    /**
     * 根据id获取用户信息
     *
     * @param id
     * @return
     */
    @Override
    public Result getUserById(int id) {
        User user = userMapper.selectById(id);
        return Result.success(user);
    }

    @Override
    public Result getUserByToken(String token) {
        if (null == token) {
            return Result.build(1, "没有登陆权限");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("token", token);
        User user = userMapper.selectOne(queryWrapper);
        if (user != null) {
            user.setPassword("***");
            user.setToken("***");
            return Result.success(user);
        }
        return Result.build(1, "获取数据失败");
    }


}
